<?php
declare (strict_types=1);

namespace app\common\model;
use think\model\relation\BelongsTo;

/**
 * 开票申请
 */
class OrderInvoice extends Base
{
    protected $name = 'order_invoice';

    public function orders(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uid', 'id');
    }

    public function business(): BelongsTo
    {
        return $this->belongsTo(Business::class, 'business_id', 'id');
    }

    public function getStatusNameAttr($value, $data)
    {
        switch ($data['status']){
            case 1:
                return '申请中';
            case 2:
                return '已开票';
            case 3:
                return '已驳回';
            default:
                return '未知';
        }
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '记录不存在'];
            }
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '记录已审核，请勿重复审核'];
            }

            $info->reject_msg = $param['reject_msg'];
            $info->status = $param['type'];
            $info->admin_name = $admin->admin_name;
            $info->audit_time = date("Y-m-d H:i:s");
            $info->save();

            Order::where('id', $info->order_id)->save(['invoice_status'=>$info->status]);
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
